/*
 * 
 * LegendShop 多用户商城系统
 * 
 *  版权所有,并保留所有权利。
 * 
 */
package com.legendshop.oa.filter;

import com.legendshop.oa.filter.handler.XssHttpServletRequestWrapper;
import com.legendshop.oa.handler.RequestHolder;
import com.legendshop.oa.security.UserDetail;
import com.legendshop.oa.security.UserManager;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Date;

/**
 * 在启动类中定义.
 */
public class LegendFilter implements Filter {


	@Override
	public void init(FilterConfig filterConfig) throws ServletException {

	}

	@Override
	public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
		HttpServletRequest request = (HttpServletRequest)servletRequest;
		HttpServletResponse response = (HttpServletResponse)servletResponse;

		String uri = request.getRequestURI();
		boolean isSupportUrl = supportURL(uri);

        if (isSupportUrl) {
        	//XSS 防止攻击
            XssHttpServletRequestWrapper wrapperRequest = new XssHttpServletRequestWrapper(request);
            RequestHolder.setRequest(wrapperRequest);


            //2. 检查用户密码更新时间
			UserDetail userDetail = UserManager.getUser(request);
			if(userDetail != null){
				boolean isUserNeedChangePassword = needChangePassword(uri, userDetail);
				if(isUserNeedChangePassword){
					request.getRequestDispatcher("/admin/passwd/load").forward(servletRequest, servletResponse);
				}
				
			}
            filterChain.doFilter(wrapperRequest, response);
        }else{
            filterChain.doFilter(request, response);
        }

	}

	/**
	 * 检查密码的修改时间，要限定时间修改密码
	 * @param userDetail
	 * @return
	 */
	private boolean needChangePassword(String uri,  UserDetail userDetail) {

		//特定的URL不过滤
		if(uri == null || uri.indexOf("/passwd") > 0 || uri.indexOf("/updatePwd") > 0){//更新密码的页面不过滤
			return false;
		}

		if(userDetail == null){
			return false;
		}

		if(userDetail.getChangePass() != null && userDetail.getChangePass().intValue() == 1){//需要修改密码
			return true;
		}

		//超时校验密码
		if(userDetail.getPassChangeDate() != null && userDetail.getPassChangeDate().before(new Date())){
			return true;
		}
		return false;
	}


	/**
	 * 不包括有后缀的URL,只是支持Controller的动作（不带后缀）
	 *
	 * @param url
	 * @return
	 */
	private boolean supportURL(String url) {
		if (url == null) {
			return false;
		}
		return url.indexOf(".") < 0;
	}

	@Override
	public void destroy() {

	}


}
